from rest_framework import serializers
from rest_framework.viewsets import ModelViewSet
from labor_price.models import MaterialsClassify
import json
from rest_framework.decorators import action
from rest_framework.response import Response


class MaterialsClassifySerializer(serializers.ModelSerializer):
    class Meta:
        model = MaterialsClassify
        fields = '__all__'


class MaterialsClassifyView(ModelViewSet):
    queryset = MaterialsClassify.objects.all()  # 查询集
    serializer_class = MaterialsClassifySerializer  # 序列化器

    # 删除
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({'msg': "删除成功", 'code': 201})

    def perform_destroy(self, instance):
        # 递归
        def digui(par):
            if isinstance(par, MaterialsClassify):
                par = [(par.id, )]
            parentClass = MaterialsClassify.objects.filter(pid__in=sum(par, ())).values_list('id')

            if not parentClass:
                MaterialsClassify.objects.filter(id=instance.id).update(status=False)
                return

            parentClass.update(status=False)
            digui(parentClass)

        # 开始执行
        digui(instance)

    @action(methods=['get'], detail=False)
    def batch_del(self, request):
        del_list = request.GET.get('del_list')
        del_list = json.loads(del_list)
        try:
            for i in (del_list):
                MaterialsClassify.objects.get(id=i).delete()
        except:
            return Response({'msg': "批量删除失败", 'code': 400, 'data': '存在关联数据；不允许删除'})
        return Response({'msg': "批量删除成功", 'code': 200})
